package com.syf.core.kit.resource;


import lombok.extern.slf4j.Slf4j;

import java.util.Map;
import java.util.concurrent.ConcurrentHashMap;

/**
 * kit资源释放的管理器
 */
@Slf4j
public class KitResourceReleaseController {
    private static final ConcurrentHashMap<String, ThreadLocal<DelegatedResource>> resourceThreadLocals = new ConcurrentHashMap<>();

    private static KitResourceReleaseController INSTANCE;

    private KitResourceReleaseController() {
    }

    public static KitResourceReleaseController getInstance() {
        if (INSTANCE == null) {
            INSTANCE = new KitResourceReleaseController();
            return INSTANCE;
        }

        throw new RuntimeException("KitResourceReleaseController对象只能获取一次，确保只有service actuator能获取！");
    }

    /**
     * 注册
     */
    static void registerResourceReleaser(String resourceName) {
        if (resourceThreadLocals.get(resourceName) == null) {
            resourceThreadLocals.putIfAbsent(resourceName, new ThreadLocal<DelegatedResource>());
        }
    }

    /**
     * 注销
     */
    static void unregisterResourceReleaser(String resourceName) {
        resourceThreadLocals.remove(resourceName);
    }

    /**
     * 获取ThreadLocal
     */
    static ThreadLocal<DelegatedResource> getThreadLocal(String resourceName) {
        return resourceThreadLocals.get(resourceName);
    }

    /**
     * 释放所有的资源，这个只有service actuator可以操作
     */
    public void releaseAll() {
        for (Map.Entry<String, ThreadLocal<DelegatedResource>> entry : resourceThreadLocals.entrySet()) {
            if (entry.getValue().get() != null) {
                if (log.isDebugEnabled()) {
                    log.debug("统一释放kit的资源，当前被释放的资源名称：{}", entry.getKey());
                }
                entry.getValue().get().releaseResource();
                entry.getValue().remove();
            }

        }
    }
}
